package cn.lliiooll.config;

import cn.lliiooll.util.Utils;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.YamlConfiguration;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class SubConfig {

    public final String name;
    private final File dir;
    private final File file;
    private final YamlConfiguration config = new YamlConfiguration();
    public final List<String> list = new ArrayList<>();

    public SubConfig(String name, File subDir) {
        this.name = name;
        this.dir = subDir;
        this.file = new File(this.dir, name.endsWith(".yml") ? name : name + ".yml");

    }

    public void append(String arg) {
        list.add(arg);
        save();
    }

    public void append(int line, String arg) {
        list.add(line, arg);
        save();
    }

    public void delete(int line) {
        list.remove(line);
        save();
    }

    public int size() {
        return list.size();
    }

    public List<String> sizeList() {
        List<String> ls = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            ls.add(ls + "");
        }
        return ls;
    }

    public void create() {
        try {
            if (!this.file.exists()) {
                this.file.createNewFile();
                this.reload();
                this.config.set("list", this.list);
                this.save();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            this.reload();
        }
    }

    public void save() {
        try {
            this.config.set("list", list);
            this.config.save(this.file);
            Utils.parseKey2Notes(this.file);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void reload() {
        try {
            this.config.loadFromString(Utils.parseNotes2Key(this.file));
            this.list.clear();
            this.list.addAll(this.config.getStringList("list"));
        } catch (InvalidConfigurationException e) {
            e.printStackTrace();
        }
    }

    public void remove() {
        this.file.delete();
    }
}
